package gcs.spl.example.imageprocess;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;


import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class MainActivity extends Activity {

	public final static int BUFFER_MAXSIZE = 100;
	public final static int BUFFER_CORESIZE = 50;
	public final static int RESOURCE_IMAGES = 20;
	public int currentImageCount = 0;
	byte[][] imagesResource;
	public static Handler handler;
	boolean isRunning = false;
	Random randShow = new Random();
	Random randLoad = new Random();
	Bitmap bitmap;
	Button btnTaskControl;
	ImageView imageView;
	ProgressBar bufferProgress;
	RadioGroup showSpeed;
	Object synObject = new Object();
	
	int[] speed = {50, 100, 150};
	int showRate = 100;
	private Handler timerHandler = new Handler();
	
	private Runnable runnable = new Runnable() {
		
		public void run() {
			// TODO Auto-generated method stub
			if(isRunning) {
				timerHandler.postDelayed(runnable, showRate);
				synchronized(synObject) {
					if(currentImageCount > 0 && imagesResource != null) {
							bitmap = BitmapFactory.decodeByteArray(imagesResource[currentImageCount - 1], 0, imagesResource[currentImageCount - 1].length);
							imagesResource[currentImageCount - 1] = null;
							currentImageCount--;
							imageView.setImageBitmap(bitmap);
							bufferProgress.setProgress(currentImageCount);
						}
						
					}
			}
		}

	};
	
	private Runnable loadTask = new Runnable() {
	     
		public void run() {
			while(isRunning) {
				try {
					Thread.sleep(100);
					synchronized(synObject) {
						if(currentImageCount <= BUFFER_CORESIZE) {
							//BufferedReader buffer = new BufferedReader(new InputStreamReader(getAssets().open("icon01.png")));
							int randIndex = randLoad.nextInt(RESOURCE_IMAGES);
							
							// THIS TASK SHOULD MOVE OUT
							InputStream byteArrInput = getAssets().open("icon" + randIndex + ".png", AssetManager.ACCESS_BUFFER);
							
							if(byteArrInput != null) {
								byte[] buf = new byte[byteArrInput.available()];
								int length = byteArrInput.read(buf);
								
								if(length > 0) {
									currentImageCount++;
									imagesResource[currentImageCount - 1] = buf;
									runOnUiThread(new Runnable() {				
										public void run() {
											bufferProgress.setProgress(currentImageCount);
										}
									});
								}
							}
						}
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};
	
	Thread loadThread;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handler = getWindow().getDecorView().getHandler();
        imagesResource = new byte[100][];
        btnTaskControl = (Button) findViewById(R.id.button1);
        imageView = (ImageView) findViewById(R.id.imageView1);
        bufferProgress = (ProgressBar) findViewById(R.id.progressBar1);
        showSpeed = (RadioGroup) findViewById(R.id.radioGroup1);
        showSpeed.check(R.id.radio1);
        showSpeed.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				int radioButtonID = group.getCheckedRadioButtonId();
				View radioButton = group.findViewById(radioButtonID);
				int idx = group.indexOfChild(radioButton);
				showRate = speed[idx];
			}
		});
        
        btnTaskControl.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(isRunning) {
					btnTaskControl.setText("Start");
					isRunning = false;
					loadThread.interrupt();
					loadThread = null;
				} else {
					btnTaskControl.setText("Stop");
					isRunning = true;
					timerHandler.postDelayed(runnable, 100);
					loadThread = new Thread(loadTask);
					loadThread.start();
				}
			}
		});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	@Override
	protected void onDestroy() {
		loadThread.interrupt();
		super.onDestroy();
	}
    
    
}
